package com.comtop.topcloud.device.service.impl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.comtop.topcloud.device.model.influxdb.DeviceReportingDataModel;
import com.comtop.topcloud.device.model.influxdb.DeviceReportingDataParamModel;
import com.comtop.topcloud.device.service.DeviceReportingDataService;
import org.springframework.stereotype.Service;
import plus.ojbk.influxdb.core.InfluxdbTemplate;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Stream;


@Service
public class DeviceReportingDataServiceImpl  implements DeviceReportingDataService {


    @Resource
    private  InfluxdbTemplate influxdbTemplate;


    public List<DeviceReportingDataModel> buildQuery(DeviceReportingDataParamModel params){
        StringBuilder query= doQuery(params);
        query.append(" ORDER BY timestamp DESC LIMIT 500");
        return  influxdbTemplate.selectList(query.toString(),DeviceReportingDataModel.class);

    }





    private void validateParams(DeviceReportingDataParamModel params) {
        // 时间必填校验
        if (params.getStartTime() == null || params.getEndTime() == null) {
            throw new IllegalArgumentException("时间范围参数必填");
        }

        // 时间范围校验
        long duration = params.getEndTime() - params.getStartTime();
        if (duration > 900_000 || duration <= 0) {
            throw new IllegalArgumentException("时间范围需在1秒至15分钟之间");
        }

        // Tag必填校验
        if (Stream.of(params.getDeviceId(), params.getProjectId(), params.getTagName(),
                        params.getMonitorId(), params.getOrgId(), params.getProductKey())
                .allMatch(StringUtils::isEmpty)) {
            throw new IllegalArgumentException("至少需要指定一个Tag参数");
        }
    }


    private Boolean addTagCondition(StringBuilder query, String fieldName, String value,Boolean andFlg) {
        if(value != null && !value.isEmpty()) {
            if(andFlg){
                query.append(" AND ");
            }
            query.append("  ").append(fieldName).append("='").append(value).append("'");
            andFlg=true;
        }
        return  andFlg;
    }

    private  StringBuilder    doQuery(DeviceReportingDataParamModel params){
        validateParams(params);
        StringBuilder query = new StringBuilder(1024);
        query.append("SELECT * FROM iot_device_reporting_data_pro WHERE ");
        Boolean andFlg= new Boolean(false);
        if(params.getStartTime()!=null){
            query.append("timestamp >= ").append(params.getStartTime());
            andFlg=true;
        }

        if(params.getEndTime()!=null){
            query.append("timestamp <= ").append(params.getEndTime());
            andFlg=true;
        }
        andFlg=addTagCondition(query, "device_id", params.getDeviceId(),andFlg);
        andFlg=addTagCondition(query, "project_id", params.getProjectId(),andFlg);
        andFlg=addTagCondition(query, "tag_name", params.getTagName(),andFlg);
        andFlg = addTagCondition(query, "monitor_id", params.getMonitorId(), andFlg);
        andFlg = addTagCondition(query, "org_id", params.getOrgId(), andFlg);
        addTagCondition(query, "product_key", params.getProductKey(), andFlg);
        return  query;
    }

    public DeviceReportingDataModel  selectOne(DeviceReportingDataParamModel params){
        StringBuilder query=   doQuery(params);
        query.append(" ORDER BY timestamp DESC LIMIT 1");
        List<DeviceReportingDataModel>   result= influxdbTemplate.selectList(query.toString(),DeviceReportingDataModel.class);
        return result.isEmpty() ? null : result.get(0);
    }











}
